package com.shiwaixiangcun.customer.module.mall

import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.util.Log
import android.view.View
import butterknife.ButterKnife
import com.chad.library.adapter.base.BaseQuickAdapter
import com.google.gson.reflect.TypeToken
import com.jaeger.recyclerviewdivider.RecyclerViewDivider
import com.lzy.okgo.OkGo
import com.lzy.okgo.callback.StringCallback
import com.lzy.okgo.model.HttpParams
import com.lzy.okgo.model.Response
import com.shiwaixiangcun.customer.GlobalApi
import com.shiwaixiangcun.customer.GlobalConfig
import com.shiwaixiangcun.customer.R
import com.shiwaixiangcun.customer.adapter.AdapterGoodList
import com.shiwaixiangcun.customer.base.BaseActivity
import com.shiwaixiangcun.customer.entity.ElementBean
import com.shiwaixiangcun.customer.entity.ResponseEntity
import com.shiwaixiangcun.customer.event.EventUtil
import com.shiwaixiangcun.customer.event.SimpleEvent
import com.shiwaixiangcun.customer.utils.AppSharePreferenceMgr
import com.shiwaixiangcun.customer.utils.JsonUtil
import com.shiwaixiangcun.customer.widget.CustomLoadMoreView
import kotlinx.android.synthetic.main.activity_good_list.*
import kotlinx.android.synthetic.main.top_bar_white.*
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.*


/**
 * 商品列表
 *
 * @author Administrator
 */
class GoodListActivity : BaseActivity(), View.OnClickListener {

    companion object {

        private val QUALITY_GOOD = 1
        private val HOT_GOOD = 2
        private val NEW_GOOD = 3
        private val DAILY_CHOOSE = 4

    }

    private var flag = 0
    private var type: String? = null
    private val mGoodList = ArrayList<ElementBean.ElementsBean>()
    var mAdapterGoodList: AdapterGoodList? = null
    /**
     * 当前Page
     */
    private var mCurrentPage = GlobalConfig.first_page

    /**
     * 每页显示的数目
     */
    private val mPageSize = GlobalConfig.page_size
    private var siteID: Int = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_good_list)
        EventUtil.getInstance().register(this)
        ButterKnife.bind(this)
        siteID = AppSharePreferenceMgr.get(mContext, GlobalConfig.CURRENT_SITE_ID, 20) as Int
        initData()
        initViewAndEvent()
    }

    override fun onDestroy() {
        super.onDestroy()
        EventUtil.getInstance().unregister(this)
    }

    override fun onRestart() {
        super.onRestart()
        mCurrentPage = 1
        requestData(type, flag, mCurrentPage, mPageSize, false)
    }

    private fun initViewAndEvent() {
        when (flag) {

            QUALITY_GOOD -> tv_page_name.text = "品质好货"
            HOT_GOOD -> tv_page_name.text = "热卖商品"
            NEW_GOOD -> tv_page_name.text = "新品特卖"
            DAILY_CHOOSE -> tv_page_name.text = "每日精选"
            else -> {
            }
        }


        mAdapterGoodList = AdapterGoodList(mGoodList)
        back_left.setOnClickListener(this)
        rv_good_list.adapter = mAdapterGoodList
        rv_good_list.layoutManager = LinearLayoutManager(this)
        mAdapterGoodList?.onItemClickListener = BaseQuickAdapter.OnItemClickListener { adapter, view, position ->
            val bundle = Bundle()
            bundle.putInt("goodId", mGoodList[position].goodsId)
            readyGo(GoodDetailActivity::class.java, bundle)
        }


        mAdapterGoodList?.setLoadMoreView(CustomLoadMoreView())
        mAdapterGoodList?.setOnLoadMoreListener({
            mCurrentPage++
            requestData(type, flag, mCurrentPage, mPageSize, true)
        }, rv_good_list)

        refreshLayout.setOnRefreshListener {
            mCurrentPage = 1
            mAdapterGoodList?.setEnableLoadMore(false)
            requestData(type, flag, mCurrentPage, mPageSize, false)
        }


        val divider = RecyclerViewDivider.Builder(this)
                .setOrientation(RecyclerViewDivider.VERTICAL)
                .setStyle(RecyclerViewDivider.Style.BETWEEN)
                .setSize(0.5f)
                .setMarginLeft(16f)
                .setMarginRight(16f)
                .setEndSkipCount(1)
                .setColorRes(R.color.color_divider_0_1)
                .build()
        rv_good_list.addItemDecoration(divider)


    }

    private fun initData() {
        val bundle = intent.extras
        type = bundle!!.getString("type")
        flag = bundle.getInt("flag")
        requestData(type, flag, mCurrentPage, mPageSize, false)

    }

    /**
     * 请求数据
     *
     * @param type 请求的类型
     * @param flag 更新界面的标志
     */
    fun requestData(type: String?, flag: Int, start: Int, size: Int, isLoadMore: Boolean) {

        val params = HttpParams()
        params.put("goodsSubjectValue", type)
        params.put("page.pn", start)
        params.put("page.size", size)
        params.put("siteId", siteID)
        OkGo.get<String>(GlobalApi.getGuessLike)
                .params(params)
                .execute(object : StringCallback() {
                    override fun onError(response: Response<String>?) {
                        super.onError(response)
                        mAdapterGoodList?.loadMoreFail()
                        refreshLayout.finishRefresh()
                        mAdapterGoodList?.setEnableLoadMore(true)
                    }

                    override fun onSuccess(response: Response<String>) {
                        val jsonString = response.body()
                        Log.e(BUG_TAG, response.rawCall.request().toString())
                        val dataType = object : TypeToken<ResponseEntity<ElementBean>>() {
                        }.type
                        val data = JsonUtil.fromJson<ResponseEntity<ElementBean>>(jsonString, dataType) ?: return

                        when (data.responseCode) {
                            1001 -> {
                                val elements = data.data.elements
                                val listSize = if (elements.isEmpty()) 0 else elements!!.size
                                if (isLoadMore) {
                                    if (listSize > 0) {
                                        EventUtil.getInstance().post(SimpleEvent(SimpleEvent.UPDATE_GOOD_LIST, flag, data.data))
                                    }
                                    if (listSize == 0 || listSize < mPageSize) {
                                        mAdapterGoodList?.loadMoreEnd(false)
                                    } else {
                                        mAdapterGoodList?.loadMoreComplete()
                                    }
                                } else {
                                    refreshLayout.finishRefresh()
                                    mAdapterGoodList?.setEnableLoadMore(true)
                                    if (listSize == 0) {
                                        cl_nodata.visibility = View.VISIBLE
                                    } else {
                                        mGoodList.clear()
                                        EventUtil.getInstance().post(SimpleEvent(SimpleEvent.UPDATE_GOOD_LIST, flag, data.data))
                                    }
                                }
                            }
                            else -> {
                            }
                        }
                    }
                })

    }

    override fun onClick(view: View) {
        when (view.id) {
            R.id.back_left -> finish()

        }
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun handleEvent(simpleEvent: SimpleEvent) {
        if (simpleEvent.mEventType != SimpleEvent.UPDATE_GOOD_LIST) {
            return
        }
        when (simpleEvent.mEventValue) {
        //更新品质好货
            QUALITY_GOOD -> {
                val data = simpleEvent.data as ElementBean
                mGoodList.addAll(data.elements)
                mAdapterGoodList?.notifyDataSetChanged()
            }

        //更新热卖商品
            HOT_GOOD -> {
                val hotData = simpleEvent.data as ElementBean
                mGoodList.addAll(hotData.elements)
                mAdapterGoodList?.notifyDataSetChanged()
            }
        //更新 新品热卖
            NEW_GOOD -> {
                val newData = simpleEvent.data as ElementBean
                mGoodList.addAll(newData.elements)
                mAdapterGoodList?.notifyDataSetChanged()
            }
        //更新每日精选
            DAILY_CHOOSE -> {
                val jingxuanData = simpleEvent.data as ElementBean
                mGoodList.addAll(jingxuanData.elements)
                mAdapterGoodList?.notifyDataSetChanged()
            }
            else -> {
            }
        }
    }

}
